<!DOCTYPE html>
<html lang="zh-cn">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>pako.js简单使用 - Foryun - Share</title>
  <meta name="renderer" content="webkit" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

<meta name="theme-color" content="#f8f5ec" />
<meta name="msapplication-navbutton-color" content="#f8f5ec">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="#f8f5ec">


<meta name="author" content="Danic" /><meta name="description" content="pako.js是一款可以对内容进行压缩/解压的js，它的主要代码借鉴zlib。(zlib在1995年发表，它的内部使用DEFLATE算法，而" /><meta name="keywords" content="Blog, IT, Share, Record" />






<meta name="generator" content="Hugo 0.81.0 with theme even" />


<link rel="canonical" href="http://foryun.com.cn/post/share/pako.js%E7%AE%80%E5%8D%95%E4%BD%BF%E7%94%A8/" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">

<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<link href="/sass/main.min.af7fd1da18d66c2b017df5b4cae508ef44cfcac3fb4c7c7a327fe4f4f9e28b08.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.css" integrity="sha256-7TyXnr2YU040zfSP+rEcz29ggW4j56/ujTPwjMzyqFY=" crossorigin="anonymous">


<meta property="og:title" content="pako.js简单使用" />
<meta property="og:description" content="pako.js是一款可以对内容进行压缩/解压的js，它的主要代码借鉴zlib。(zlib在1995年发表，它的内部使用DEFLATE算法，而" />
<meta property="og:type" content="article" />
<meta property="og:url" content="http://foryun.com.cn/post/share/pako.js%E7%AE%80%E5%8D%95%E4%BD%BF%E7%94%A8/" /><meta property="article:section" content="post" />
<meta property="article:published_time" content="2021-03-15T15:22:43&#43;04:00" />
<meta property="article:modified_time" content="2021-03-15T15:22:43&#43;04:00" />

<meta itemprop="name" content="pako.js简单使用">
<meta itemprop="description" content="pako.js是一款可以对内容进行压缩/解压的js，它的主要代码借鉴zlib。(zlib在1995年发表，它的内部使用DEFLATE算法，而"><meta itemprop="datePublished" content="2021-03-15T15:22:43&#43;04:00" />
<meta itemprop="dateModified" content="2021-03-15T15:22:43&#43;04:00" />
<meta itemprop="wordCount" content="2350">
<meta itemprop="keywords" content="pako," /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="pako.js简单使用"/>
<meta name="twitter:description" content="pako.js是一款可以对内容进行压缩/解压的js，它的主要代码借鉴zlib。(zlib在1995年发表，它的内部使用DEFLATE算法，而"/>

<!--[if lte IE 9]>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
<![endif]-->

<!--[if lt IE 9]>
  <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
<![endif]-->

</head>
<body>
  <div id="mobile-navbar" class="mobile-navbar">
  <div class="mobile-header-logo">
    <a href="/" class="logo">Foryun</a>
  </div>
  <div class="mobile-navbar-icon">
    <span></span>
    <span></span>
    <span></span>
  </div>
</div>
<nav id="mobile-menu" class="mobile-menu slideout-menu">
  <ul class="mobile-menu-list">
    <a href="/">
        <li class="mobile-menu-item">Home</li>
      </a><a href="/post/">
        <li class="mobile-menu-item">Archives</li>
      </a><a href="/tags/">
        <li class="mobile-menu-item">Tags</li>
      </a><a href="/categories/">
        <li class="mobile-menu-item">Categories</li>
      </a><a href="/diary/">
        <li class="mobile-menu-item">Diary</li>
      </a><a href="/record/">
        <li class="mobile-menu-item">Record</li>
      </a><a href="/game/">
        <li class="mobile-menu-item">Game</li>
      </a><a href="/about/">
        <li class="mobile-menu-item">About</li>
      </a>
  </ul>

  


</nav>

  <div class="container" id="mobile-panel">
    <header id="header" class="header">
        <div class="logo-wrapper">
  <a href="/" class="logo">Foryun</a>
</div>





<nav class="site-navbar">
  <ul id="menu" class="menu">
    <li class="menu-item">
        <a class="menu-item-link" href="/">Home</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/post/">Archives</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/tags/">Tags</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/categories/">Categories</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/diary/">Diary</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/record/">Record</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/game/">Game</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/about/">About</a>
      </li>
  </ul>
</nav>

    </header>

    <main id="main" class="main">
      <div class="content-wrapper">
        <div id="content" class="content">
          <article class="post">
    
    <header class="post-header">
      <h1 class="post-title">pako.js简单使用</h1>

      <div class="post-meta">
        <span class="post-time"> 2021-03-15 </span>
        <div class="post-category">
            <a href="/categories/share/"> Share </a>
            </div>
          <span class="more-meta"> 约 2350 字 </span>
          <span class="more-meta"> 预计阅读 5 分钟 </span>
        <span id="busuanzi_container_page_pv" class="more-meta"> <span id="busuanzi_value_page_pv"><img src="/img/spinner.svg" alt="spinner.svg"/></span> 次阅读 </span>
      </div>
    </header>

    <div class="post-toc" id="post-toc">
  <h2 class="post-toc-title">文章目录</h2>
  <div class="post-toc-content always-active">
    <nav id="TableOfContents">
  <ul>
    <li>
      <ul>
        <li>
          <ul>
            <li></li>
          </ul>
        </li>
      </ul>
    </li>
  </ul>
</nav>
  </div>
</div>
    <div class="post-content">
      <p>pako.js是一款可以对内容进行压缩/解压的js，它的主要代码借鉴zlib。(zlib在1995年发表，它的内部使用DEFLATE算法，而DEFLATE算法用到了Huffman算法和LZ77算法；每个语言都有zlib的实现，我们可以认为pako是zlib在js上的实现，pako中方法的参数都是参考zlib)</p>
<p>pako.js的github地址: <a href="https://github.com/nodeca/pako">pako</a>，文档地址： <a href="http://nodeca.github.io/pako/">pako文档</a>。下面是一个简单可以对文本内容压缩/解压的demo页面:</p>
<p><a href="http://www.qiutianaimeili.com/html/_page/2019/12/source/pako/example.html">=&gt; pako进行压缩/解压</a>(二维码)</p>
<h4 id="基本用法">基本用法</h4>
<p>pako最基本的两个方法就是deflate（压缩）和inflate（解压）方法：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">/*****压缩*****/var input = pako.deflate([49,50]);/*input为数组*/var input = pako.deflate([49,50],{/*input为字符串*/    to:&#39;string&#39;,    level:6,/*0表示不压缩，1表示压缩时间最快，压缩率最小；9表示压缩率最大，时间最长；默认6*/});var input = pako.deflate(&#39;12&#39;);/*input为数组*//*****解压*****/output= pako.inflate(input);/*结果:[49,50]*/output= pako.inflate(input,{/*结果:12*/    to:&#39;string});
</code></pre></td></tr></table>
</div>
</div><p>需要注意的level，它可以设置压缩程度，0表示不压缩，1-9，数字越大表示压缩率越高，需要的时间越久。</p>
<h4 id="new-deflatenew-inflate">new Deflate,new Inflate</h4>
<p>上面那种是一次性拿到所有数据进行压缩/解压，如果数据不是一次行得到，而是每次得到一部分，那么可以用new Deflate/new Inflate去处理：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">/*压缩*/var chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]), chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);var deflate = new pako.Deflate({ level: 3});deflate.push(chunk1, false);deflate.push(chunk2, true); // true -&gt;最后一个块if (deflate.err) { throw new Error(deflate.err); }console.log(deflate.result);/*解压*/var chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]), chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);var inflate = new pako.Inflate();inflate.push(chunk1, false);inflate.push(chunk2, true); // true -&gt; 最后一个块if (inflate.err) { throw new Error(inflate.err); }console.log(inflate.result);
</code></pre></td></tr></table>
</div>
</div><p>配置参数和之前差不多，只不过这种多了一个push方法，可以分批将数据组装起来。</p>
<p>我们一般在Deflate（压缩）的时候设置压缩级别(level)，在InFlate(解压)的时候不用去设置压缩级别，因为压缩的时候已经将压缩的信息写在格式头部了，下面会有介绍。</p>
<h4 id="deflaterawinflateraw">deflateRaw,inflateRaw</h4>
<p>defalteRaw表示压缩的时候只有压缩内容，没有格式头，我们先来看看用deflate压缩和defalteRaw压缩有什么不一样：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">let input1=pako.deflate([49,50],{    level:1});/*结果：Uint8Array(10) [120, 1, 51, 52, 2, 0, 0, 150, 0, 100]*/let input2=pako.deflateRaw([49,50],{    level:1});/*结果：Uint8Array(4) [51, 52, 2, 0]*/
</code></pre></td></tr></table>
</div>
</div><p>我们可以发现，deflateRaw得到的数据是defalte的一部分，defalte比deflateRaw多了一些东西，前面多了120，1，后面多了0，150，0，100 。那么多出来的是什么东西呢？</p>
<p><img src="http://active.qiutianaimeili.com/pako_e1.png" alt="img"><img src="http://active.qiutianaimeili.com/pako_e1.png" alt="img"></p>
<p>上面是zlib保存数据的格式，我们可以看到，真正的压缩内容为Compressed Data，它的前面和后面都有内容，这些内容就是格式头了，里面记录一些压缩的基本信息，之前说到解压的时候不用传level，因为格式头里面都包含了。</p>
<p>注意:deflateRaw压缩的内容只能用inflateRaw解压，因为inflateRaw不检查格式头，而infalte要检查格式头，如果直接用inflateRaw解压就报错了。</p>
<h4 id="level-0和1-9">level 0和1-9</h4>
<p>还记得之前提到的level:0，不压缩码？我们利用defalteRaw方法看看，到底何为不压缩，何为压缩：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">/*deflateRaw获取level:0的格式头和真正内容*/let input3 = pako.deflate([49, 50, 51,52,53,54,55,56,57,58,59,60], {    level: 0});/*结果：Uint8Array(23) [120, 1, 1, 12, 0, 243, 255, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 16, 24, 2, 143]*/let input31 = pako.deflateRaw([49, 50, 51,52,53,54,55,56,57,58,59,60], {    level: 0});/*结果:Uint8Array(17) [1, 12, 0, 243, 255, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60]*//*-------------------------------------------------------------------------------------------*//*deflateRaw获取level:1的格式头和真正内容*/let input4 = pako.deflate([49, 50, 51,52,53,54,55,56,57,58,59,60], {    level: 1});/*结果:Uint8Array(20) [120, 1, 51, 52, 50, 54, 49, 53, 51, 183, 176, 180, 178, 182, 1, 0, 16, 24, 2, 143]*/let input41 = pako.deflateRaw([49, 50, 51,52,53,54,55,56,57,58,59,60], {    level: 1});/*结果:Uint8Array(14) [51, 52, 50, 54, 49, 53, 51, 183, 176, 180, 178, 182, 1, 0]*/
</code></pre></td></tr></table>
</div>
</div><p>我们可以发现level:0压缩后的结果为：[1, 12, 0, 243, 255, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60]，原始内容为：[49, 50, 51,52,53,54,55,56,57,58,59,60]，也就是说压缩的内容里面有前面完整的内容，甚至前面还多了一些内容。因此可以知道level:0真的是没有发生压缩。</p>
<p>level:1压缩后的内容和压缩前的内容没有对应关系，内部应该是用LZ77算法实现（可以自行百度，了解下LZ77算法），LZ77里面有滑动窗口，预存区之类概念，因此level（1-9），级别越高，应该就是这些区域更大，压缩率更高，时间更长。</p>
<h4 id="gzipungzip">gzip,ungzip</h4>
<p>上面我们了解到了什么是格式头，其实除了deflate有格式头，还有一种格式头：gzip，它和defalte类似，也包含了压缩的数据，只不过压缩头不一样：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">let input6 = pako.gzip([49, 50],);/*结果:Uint8Array(22) [31, 139, 8, 0, 0, 0, 0, 0, 0, 3, 51, 52, 2, 0, 205, 68, 83, 79, 2, 0, 0, 0]*/let input61 = pako.deflateRaw([49, 50]);/*结果:Uint8Array(4) [51, 52, 2, 0]*/
</code></pre></td></tr></table>
</div>
</div><p>我们可以看到压缩内容的前面和后面都有很多内容，比defalte的要多得多。确实，因为gzip的格式头里面存储的内容比defalte要多：</p>
<p><img src="http://active.qiutianaimeili.com/pako_e2.png" alt="img"></p>
<p>在pako.js中可以也可以配置gzip的这种格式头：</p>
<p><img src="http://active.qiutianaimeili.com/pako_e3.png" alt="img"></p>
<p>用gzip压缩的内容,infalte和ungzip都是可以解压的，因为解压的内容只包含数据，不含格式头。</p>

    </div>

    <div class="post-copyright">
  <p class="copyright-item">
    <span class="item-title">文章作者</span>
    <span class="item-content">Danic</span>
  </p>
  <p class="copyright-item">
    <span class="item-title">上次更新</span>
    <span class="item-content">
        2021-03-15
        
    </span>
  </p>
  
  
</div>
<footer class="post-footer">
      <div class="post-tags">
          <a href="/tags/pako/">pako</a>
          </div>
      <nav class="post-nav">
        <a class="prev" href="/post/share/%E7%94%A8zlib%E5%8E%8B%E7%BC%A9%E6%88%96%E8%A7%A3%E5%8E%8B%E7%BC%A9%E5%AD%97%E8%8A%82%E6%95%B0%E7%BB%84/">
            <i class="iconfont icon-left"></i>
            <span class="prev-text nav-default">C#用Zlib压缩或解压缩字节数组</span>
            <span class="prev-text nav-mobile">上一篇</span>
          </a>
        <a class="next" href="/post/share/uri%E7%BC%96%E7%A0%81%E8%AF%A6%E8%A7%A3/">
            <span class="next-text nav-default">JavaScript及C# URI编码详解</span>
            <span class="next-text nav-mobile">下一篇</span>
            <i class="iconfont icon-right"></i>
          </a>
      </nav>
    </footer>
  </article>
        </div>
        

  <span id="/post/share/pako.js%E7%AE%80%E5%8D%95%E4%BD%BF%E7%94%A8/" class="leancloud_visitors" data-flag-title="pako.js简单使用">
		<span class="post-meta-item-text">文章阅读量 </span>
		<span class="leancloud-visitors-count">0</span>
		<p></p>
	  </span>
  <div id="vcomments"></div>
  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src='//unpkg.com/valine/dist/Valine.min.js'></script>
  <script type="text/javascript">
    new Valine({
        el: '#vcomments' ,
        appId: 'insXINA0D2ccQdcEfEcMSjgn-gzGzoHsz',
        appKey: 'HEAEkloDNn3aFg4Yr1W4iGM3',
        notify:  false ,
        verify:  false ,
        avatar:'mm',
        placeholder: '说点什么吧...',
        visitor:  true 
    });
  </script>

  

      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="social-links">
      <a href="mailto:1186976350@qq.com" class="iconfont icon-email" title="email"></a>
      <a href="https://github.com/DanicCheng" class="iconfont icon-github" title="github"></a>
      <a href="https://space.bilibili.com/2920221?spm_id_from=333.788.b_765f7570696e666f.2" class="iconfont icon-bilibili" title="bilibili"></a>
  
</div>

<div class="copyright">
  <span class="power-by">
    由 <a class="hexo-link" href="https://gohugo.io">Hugo</a> 强力驱动
  </span>
  <span class="division">|</span>
  <span class="theme-info">
    主题 - 
    <a class="theme-link" href="https://github.com/olOwOlo/hugo-theme-even">Even</a>
  </span>

  <div class="busuanzi-footer">
    <span id="busuanzi_container_site_pv"> 本站总访问量 <span id="busuanzi_value_site_pv"><img src="/img/spinner.svg" alt="spinner.svg"/></span> 次 </span>
      <span class="division">|</span>
    <span id="busuanzi_container_site_uv"> 本站总访客数 <span id="busuanzi_value_site_uv"><img src="/img/spinner.svg" alt="spinner.svg"/></span> 人 </span>
  </div>

  <span class="copyright-year">
    &copy; 
    2017 - 
    2021<span class="heart"><i class="iconfont icon-heart"></i></span><span>Foryun</span>
  </span>

  <span class="beian">
    
    备案号：<a href="https://beian.miit.gov.cn" target="_blank">粤ICP备18045119号</a>
    
  </span>

</div>

    </footer>

    <div class="back-to-top" id="back-to-top">
      <i class="iconfont icon-up"></i>
    </div>
  </div>
  
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/slideout@1.0.1/dist/slideout.min.js" integrity="sha256-t+zJ/g8/KXIJMjSVQdnibt4dlaDxc9zXr/9oNPeWqdg=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.js" integrity="sha256-XVLffZaxoWfGUEbdzuLi7pwaUJv1cecsQJQqGLe7axY=" crossorigin="anonymous"></script>



<script type="text/javascript" src="/js/main.min.c99b103c33d1539acf3025e1913697534542c4a5aa5af0ccc20475ed2863603b.js"></script>

<script id="baidu_analytics">
  var _hmt = _hmt || [];
  (function() {
    if (window.location.hostname === 'localhost') return;
    var hm = document.createElement("script"); hm.async = true;
    hm.src = "https://hm.baidu.com/hm.js?57ed19d6fdd95893edd119b86ac49dab";
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(hm, s);
  })();
</script>

<script id="baidu_push">
  (function(){
    if (window.location.hostname === 'localhost') return;
    var bp = document.createElement('script'); bp.async = true;
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
      bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
    }
    else {
      bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
  })();
</script>




</body>
</html>
